package com.dayu.frame;

import com.dayu.helper.ConfigHelper;
import com.dayu.helper.EntryHelper;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

public class SetDBFrame extends JDialog {

    private final JPanel mainPanel;
    private final CardLayout cardLayout;
    private final Map<String, Map<String, JTextField>> dbTextFields;
    private final JComboBox<String> cbDBType;

    public SetDBFrame(JFrame topFrame) {
        super(topFrame, "设置数据库连接", true);

        setSize(330, 400);
        setResizable(false);

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (screenSize.width - getWidth()) / 2;
        int y = (screenSize.height - getHeight()) / 2;
        setLocation(x, y);
        setUndecorated(true);
        getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
        setLayout(new BorderLayout());
        getRootPane().setBorder(new LineBorder(Color.BLACK, 1, true));

        dbTextFields = new HashMap<>();

        // 顶部数据库选择
        JLabel lbDataBaseType = new JLabel("数据库类型：");
        cbDBType = new JComboBox<>(new String[]{
                "MySQL",
                "Oracle",
                "PostgreSQL",
                "SqlServer",
                "MariaDB(暂不支持)",
                "TIDB(暂不支持)",
                "Cache DB (2016)(暂不支持)"});
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        topPanel.add(lbDataBaseType);
        topPanel.add(cbDBType);
        add(topPanel, BorderLayout.NORTH);

        // 主面板使用CardLayout
        cardLayout = new CardLayout();
        mainPanel = new JPanel(cardLayout);

        // MySQL组件组
        JPanel mysqlPanel = createPanel("MySQL");
        addComponentGroup(mysqlPanel, "MySQL", "主机地址:", "localhost");
        addComponentGroup(mysqlPanel, "MySQL", "端口:", "3306");
        addComponentGroup(mysqlPanel, "MySQL", "用户名:", "root");
        addComponentGroup(mysqlPanel, "MySQL", "密码:", "password");

        // Oracle组件组
        JPanel oraclePanel = createPanel("Oracle");
        addComponentGroup(oraclePanel, "Oracle", "主机地址:", "localhost");
        addComponentGroup(oraclePanel, "Oracle", "端口:", "1521");
        addComponentGroup(oraclePanel, "Oracle", "服务名:", "ORCL");
        addComponentGroup(oraclePanel, "Oracle", "用户名:", "user");
        addComponentGroup(oraclePanel, "Oracle", "密码:", "password");

        // PostgreSQL组件组
        JPanel postgresPanel = createPanel("PostgreSQL");
        addComponentGroup(postgresPanel, "PostgreSQL", "主机地址:", "localhost");
        addComponentGroup(postgresPanel, "PostgreSQL", "端口:", "5432");
        addComponentGroup(postgresPanel, "PostgreSQL", "初始数据库:", "postgres");
        addComponentGroup(postgresPanel, "PostgreSQL", "用户名:", "user");
        addComponentGroup(postgresPanel, "PostgreSQL", "密码:", "password");

        JPanel sqlServerPanel = createPanel("SqlServer");
        addComponentGroup(sqlServerPanel, "SqlServer", "主机地址:", "localhost");
        addComponentGroup(sqlServerPanel, "SqlServer", "端口:", "1433");
        addComponentGroup(sqlServerPanel, "SqlServer", "初始数据库:", "master");
        addComponentGroup(sqlServerPanel, "SqlServer", "用户名:", "user");
        addComponentGroup(sqlServerPanel, "SqlServer", "密码:", "password");
        addComponentGroup(sqlServerPanel, "SqlServer", "未测试", "SqlServer连接未测试可能存在问题");

        JPanel otherPanel = createPanel("Other");
        addComponentGroup(otherPanel, "Other", "未适配", "未适配");
        // 将各个数据库组件组添加到CardLayout面板
        mainPanel.add(mysqlPanel, "MySQL");
        mainPanel.add(oraclePanel, "Oracle");
        mainPanel.add(postgresPanel, "PostgreSQL");
        mainPanel.add(sqlServerPanel, "SqlServer");
        mainPanel.add(otherPanel, "otherPanel");

        // 包装主面板的容器
        JPanel mainContainer = new JPanel(new BorderLayout());
        mainContainer.add(mainPanel, BorderLayout.NORTH); // 将主面板靠顶部对齐
        JScrollPane scrollPane = new JScrollPane(mainContainer);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        add(scrollPane, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton btnTestConnection = new JButton("保存并关闭");
        bottomPanel.add(btnTestConnection);
        add(bottomPanel, BorderLayout.SOUTH);

        // 数据库类型选择事件
        cbDBType.addActionListener(e -> {
            String selectedDB = (String) cbDBType.getSelectedItem();
            if(EntryHelper.enableDataBaseType.contains(selectedDB))
                cardLayout.show(mainPanel, selectedDB);
            else
                cardLayout.show(mainPanel, "otherPanel");
        });

        // 默认显示MySQL组件组
        cardLayout.show(mainPanel, "MySQL");

        // 测试连接按钮事件
        btnTestConnection.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(testConnection()){
                    dispose();
                }
            }
        });

        // 加载现有配置
        if (ConfigHelper.hasConfig()) {
            String dbType = ConfigHelper.getDbType();
            String dbUrl = ConfigHelper.getDbUrl();
            String dbUser = ConfigHelper.getDbUser();
            String dbPwd = ConfigHelper.getDbPwd();
            String dbInit = ConfigHelper.getDbInit();

            Map<String, JTextField> fields = dbTextFields.get(dbType);
            if (fields != null) {
                // 分解 dbUrl 获取主机和端口
                String[] hostPort = dbUrl.split(":");
                String host = hostPort[0];
                String port = hostPort[1];

                fields.get("主机地址:").setText(host);
                fields.get("端口:").setText(port);
                fields.get("用户名:").setText(dbUser);
                fields.get("密码:").setText(dbPwd);

                if (dbType.equals("Oracle")) {
                    fields.get("服务名:").setText(dbInit);
                } else if (dbType.equals("PostgreSQL") || dbType.equals("SqlServer")) {
                    fields.get("初始数据库:").setText(dbInit);
                }
                cbDBType.setSelectedItem(dbType);
                cardLayout.show(mainPanel, dbType);
            }
        }
    }

    private JPanel createPanel(String dbType) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        dbTextFields.put(dbType, new HashMap<>());
        return panel;
    }

    private void addComponentGroup(JPanel panel, String dbType, String labelText, String textFieldText) {
        JPanel groupPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        groupPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 40)); // 固定每组高度为40，包括间隔

        JLabel label = new JLabel(labelText);
        label.setPreferredSize(new Dimension(80, 20)); // 固定标签宽度
        JTextField textField = new JTextField(textFieldText, 15);
        textField.setPreferredSize(new Dimension(200, 20)); // 固定输入框宽度

        dbTextFields.get(dbType).put(labelText, textField);

        groupPanel.add(label);
        groupPanel.add(textField);
        panel.add(groupPanel);
        panel.add(Box.createVerticalStrut(5)); // 每组之间间隔5像素
    }

    private boolean testConnection() {
        String selectedDB = (String) cbDBType.getSelectedItem();
        Map<String, JTextField> fields = dbTextFields.get(selectedDB);

        String host = fields.get("主机地址:").getText();
        String port = fields.get("端口:").getText();
        String user = fields.get("用户名:").getText();
        String password = fields.get("密码:").getText();
        String serviceName = selectedDB.equals("Oracle") ? fields.get("服务名:").getText() : null;
        String initialDatabase = selectedDB.equals("PostgreSQL") || selectedDB.equals("SqlServer")  ? fields.get("初始数据库:").getText() : null;

        String databaseUrl = String.format("%s:%s", host, port);

        String DataBaseInit = selectedDB.equals("Oracle") ? serviceName : initialDatabase != null ? initialDatabase : "";

        try{
            boolean connectionSuccessful = EntryHelper.verifyConnection(selectedDB, databaseUrl, user, password, DataBaseInit);
            if (connectionSuccessful) {
                // 保存连接信息到系统缓存
                ConfigHelper.saveConfig(selectedDB, String.format("%s:%s", host, port), user, password, DataBaseInit);
            }
            String message = connectionSuccessful ? "连接成功!" : "连接失败!";
            JOptionPane.showMessageDialog(this, message, "测试连接", JOptionPane.INFORMATION_MESSAGE);
            return connectionSuccessful;
        }catch (Exception ex){
            //ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "连接失败："+ ex.getMessage(), "测试连接", JOptionPane.INFORMATION_MESSAGE);
        }
        return false;
    }



}
